#!/bin/env python3
# coding:utf-8
import os
import sys
import yaml
from collections import OrderedDict
# obs project name, which new branch for package will be created from
obs_project = sys.argv[1]
# new branch name
branch_name = sys.argv[2]
# new branch created from
branch_from = sys.argv[3]
# community repository path
community_path = sys.argv[4]

src_yaml_file_path = os.path.join(community_path, "repository", "src-openeuler.yaml")
sigs_yaml_file_path = os.path.join(community_path, "sig", "sigs.yaml")

cmd = "osc list %s" % obs_project
pkgs = list(set(os.popen(cmd).read().split("\n")) - set(['']))

def read_yaml(file_path):
    file_msg = None
    if os.path.exists(file_path):
        with open(file_path, "r", encoding='utf-8') as f:
            file_msg = yaml.load(f, Loader=yaml.FullLoader)
    return file_msg


def write_yaml(dict_msg, file_path):
    with open(file_path, "w", encoding='utf-8') as f:
        yaml.dump(dict_msg, f, default_flow_style=False, sort_keys=False)

def add_branch():
    recycle_pkgs = []
    dict_msg = read_yaml(src_yaml_file_path)
    sigs_list = read_yaml(sigs_yaml_file_path)["sigs"]
    for sig in sigs_list:
        if sig["name"] == "sig-recycle":
            recycle_pkgs = sig["repositories"]
    if recycle_pkgs:
        for i in range(len(recycle_pkgs)):
            recycle_pkgs[i] = recycle_pkgs[i].split("/")[1]
            
    for pkg in dict_msg["repositories"]:
        flag = False
        if pkg["name"] in pkgs and pkg["name"] not in recycle_pkgs:
            for bm in pkg["branches"]:
                if bm["name"] == branch_name:
                    flag = True
                    break
            if not flag:
                pkg["branches"].append({'name': branch_name, 'type':"protected", 'create_from':branch_from})
    write_yaml(dict_msg, src_yaml_file_path)

add_branch()
